import * as storage from '@/utils/storage'
import * as types from '../mutation-types'

const state = {
  // default: false
  isSidebarCollapse: !!storage.getItem('isSidebarCollapse'),
  activeMenuIndex: null,
  routeTitleList: null,
  openedTabs: storage.getItem('openedTabs') || [{
    id: 0,
    name: 'home',
    title: '首页',
    closable: false
  }],
  currentTabName: 'home'
}
const getters = {
  isSidebarCollapse: state => state.isSidebarCollapse,
  activeMenuIndex: state => state.activeMenuIndex,
  routeTitleList: state => state.routeTitleList,
  openedTabs: state => state.openedTabs,
  currentTabName: state => state.currentTabName
}
const actions = {}
const mutations = {
  [types.TOGGLE_SIDEBAR]: state => {
    state.isSidebarCollapse = !state.isSidebarCollapse
    storage.setItem('isSidebarCollapse', state.isSidebarCollapse)
  },
  [types.SET_ACTIVE_MENU_INDEX]: (state, activeMenuIndex) => {
    state.activeMenuIndex = activeMenuIndex
  },
  [types.SET_ROUTE_TITLE_LIST]: (state, titleList) => {
    state.routeTitleList = titleList
  },
  [types.ADD_TAB]: (state, tab) => {
    let openedTabs = state.openedTabs
    if (!openedTabs.find(value => value.id === tab.id)) {
      state.openedTabs.push(tab)
      storage.setItem('openedTabs', state.openedTabs)
    }
  },
  [types.REMOVE_TAB]: (state, index) => {
    state.openedTabs.splice(index, 1)
    storage.setItem('openedTabs', state.openedTabs)
  },
  [types.SET_CURRENT_TAB_NAME]: (state, tabName) => {
    state.currentTabName = tabName
  }
}

const app = {
  state,
  getters,
  actions,
  mutations
}

export default app
